/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head.next == null) {
            return null;
        }
        ListNode pre = null, p = head, q = head;
        for (int i = 0; i < n; i++) {
            q = q.next;
        }
        while (q != null) {
            pre = p;
            p = p.next;
            q = q.next;
        }
        if (p == head) {
            return head.next;
        }
        pre.next = p.next;
        return head;
    }
}

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre = null, p = head, q = head;
        for (int i = 0; i < n; i++) {
            q = q.next;
        }
        while (q != null) {
            pre = p;
            p = p.next;
            q = q.next;
        }
        if (pre == null) {
            return head.next;
        }
        pre.next = p.next;
        return head;
    }
}
